home *** CD-ROM | disk | FTP | other *** search
/ FishMarket 1.0 / FishMarket v1.0.iso / fishies / 301-325 / disk_319 / cnewssrc / cnews.orig.lzh / libv7 / gethostname.c < prev    next >
C/C++ Source or Header  |  1989-06-27  |  2KB  |  91 lines

  1. /*
  2.  * v7 gethostname simulation
  3.  *    taken from pathalias and cleaned up.  Thanks, peter.
  4.  */
  5.  
  6. #include <stdio.h>
  7.  
  8. /* imports from libc */
  9. extern char *index(), *strncpy();
  10. extern FILE *fopen(), *popen();
  11.  
  12. /* forwards */
  13. void readhostfile();
  14.  
  15. #define MAXHOST 256
  16. #define min(a,b) ((a) < (b)? (a): (b))
  17.  
  18. static char defhost[] = "INSERT-YOUR-HOST-NAME-HERE";
  19. static char *namefiles[] = {
  20.     "/etc/whoami",
  21.     "/etc/systemid",
  22.     NULL
  23. };
  24.  
  25. int
  26. gethostname(hostname, size)
  27. register char *hostname;
  28. int size;
  29. {
  30.     register FILE *whoami;
  31.     register char **namep;
  32.  
  33.     *hostname = '\0';
  34.  
  35.     /* try files in namefiles */
  36.     for (namep = namefiles; *namep != NULL; namep++) {
  37.         readhostfile(hostname, size, *namep);
  38.         if (*hostname != '\0')
  39.             return 0;
  40.     }
  41.  
  42.     /* try /usr/include/whoami.h */
  43.     if ((whoami = fopen("/usr/include/whoami.h", "r")) != NULL) {
  44.         while (!feof(whoami)) {
  45.             char sysname[MAXHOST];
  46.  
  47.             if (fgets(sysname, MAXHOST, whoami) == NULL)
  48.                 break;
  49.             if (sscanf(sysname, "#define sysname \"%[^\"]\"",
  50.                 hostname) > 0)
  51.                 break;
  52.         }
  53.         (void) fclose(whoami);
  54.         if (*hostname != '\0')
  55.             return 0;
  56.     }
  57.  
  58.     /* ask uucp */
  59.     if ((whoami = popen("PATH=/bin:/usr/bin:/usr/ucb uuname -l", "r")) != NULL) {
  60.         register char *ptr;
  61.  
  62.         (void) fgets(hostname, size, whoami);
  63.         (void) pclose(whoami);
  64.         if ((ptr = index(hostname, '\n')) != NULL)
  65.             *ptr = '\0';
  66.     }
  67.     if (*hostname != '\0')
  68.         return 0;
  69.  
  70.     /* aw hell, i give up!  is this a real unix? */
  71.     (void) strncpy(hostname, defhost, min(sizeof defhost, size));
  72.     return 0;
  73. }
  74.  
  75. static void
  76. readhostfile(hostname, size, file)    /* read host name from file */
  77. char *hostname, *file;
  78. int size;
  79. {
  80.     register FILE *whoami;
  81.  
  82.     if ((whoami = fopen(file, "r")) != NULL) {
  83.         register char *ptr;
  84.  
  85.         (void) fgets(hostname, size, whoami);
  86.         (void) fclose(whoami);
  87.         if ((ptr = index(hostname, '\n')) != NULL)
  88.             *ptr = '\0';
  89.     }
  90. }
  91.